<template>
  <div id="student">
    <div class="main">
      <h2>智能学习助手</h2>
      <div class="chat-container">
        <!-- 左侧历史对话列表 -->
        <div class="chat-sidebar">
          <el-button type="primary" @click="startNewChat" icon="el-icon-plus">新对话</el-button>
          <ul class="chat-history">
            <li
              v-for="chat in chatList"
              :key="chat.chatID"
              :class="{ active: chat.chatID === currentChatId }"
              @click="loadChat(chat.chatID)"
            >
              {{ chat.content.slice(0, 12) }}{{ chat.content.length > 12 ? '...' : '' }}
              <i class="el-icon-delete" @click.stop="deleteChat(chat.chatID)"></i>
            </li>
          </ul>
        </div>

        <!-- 右侧对话窗口 -->
        <div class="chat-main">
          <div class="chat-log" v-if="chatLog.length">
            <div
              v-for="(msg, index) in chatLog"
              :key="index"
              :class="msg.speaker === 1 ? 'chat-user' : 'chat-ai'"
            >
              <span class="chat-content">{{ msg.content }}</span>
            </div>
          </div>
          <div v-else class="chat-empty">请开始新的对话或选择左侧历史记录</div>

          <!-- 输入框和按钮 -->
          <div class="chat-input">
            <el-input
              v-model="inputContent"
              placeholder="请输入问题"
              @keyup.enter="sendMessage"
              clearable
            />
            <el-button type="primary" @click="sendMessage">发送</el-button>
          </div>
        </div>
      </div>
    </div>

    <router-view />
    <v-footer />
  </div>
</template>

<script>
import myFooter from '@/components/student/myFooter'
import { mapState } from 'vuex'

export default {
  components: {
    'v-footer': myFooter
  },
  data() {
    return {
      flag:false,
      user: {},
      courseId: null,
      chatList: [],
      currentChatId: null,
      chatLog: [],
      inputContent: '',
    }
  },
  created() {
  this.userInfo().then(() => {
    this.courseId = this.$route.params.courseId
    this.loadChatList()
  })
},
  methods: {
    async userInfo() {
      const name = this.$cookies.get('cname')
    const id = this.$cookies.get('cid')
    this.user = { userName: name, studentId: id }
    return Promise.resolve() // 确保可以 await userInfo()
    },
    async loadChatList() {
      const res = await this.$axios.get('/api/chat/chatlist', {
        params: {
          studentID: this.user.studentId,
          courseID: 1
        }
      })
      if (res.data.code === 200) {
        this.chatList = res.data.data
      }
    },
    async startNewChat() {
      const res = await this.$axios.get('/api/chat/newchatid', {
        params: {
          studentID: this.user.studentId,
          courseID: this.courseId
        }
      })
      if (res.data.code === 200) {
        const newChatId = res.data.data
        this.currentChatId = newChatId
        this.chatLog = []
        this.loadChatList()
      }
    },
    scrollToBottom() {
  this.$nextTick(() => {
    const chatLogEl = this.$el.querySelector('.chat-log')
    if (chatLogEl) {
      chatLogEl.scrollTop = chatLogEl.scrollHeight
    }
  })
},
    async loadChat(chatID) {
      this.currentChatId = chatID
      const res = await this.$axios.get('/api/chat/chatlog', {
        params: {
          studentID: this.user.studentId,
          courseID: this.courseId,
          chatID
        }
      })
      if (res.data.code === 200) {
        this.chatLog = res.data.data
      }
    },
    async sendMessage() {
  if (!this.inputContent || !this.currentChatId) return
  const userMessage = {
    studentID: this.user.studentId,
    courseID: this.courseId,
    chatID: this.currentChatId,
    content: this.inputContent
  }

  // 添加用户提问
  this.chatLog.push({ ...userMessage, speaker: 1 })

  // 滚动到底部（用户提问后）
  this.$nextTick(() => {
    this.scrollToBottom()
  })

  // 发送请求，获取 AI 回复
  try {
    const res = await this.$axios.post('/api/chat/query', userMessage)
    if (res.data && res.data.content) {
      this.chatLog.push({ ...res.data, speaker: 2 })

      // ✅ 确保 AI 回复渲染完毕后再滚动
      this.$nextTick(() => {
        this.scrollToBottom()
      })
    } else {
      this.$message.error('AI 未能正确回复')
    }
  } catch (err) {
    this.$message.error('请求失败')
  }

  this.inputContent = ''
},
    async deleteChat(chatID) {
      await this.$axios.delete('/api/chat/delete', {
        data: {
          studentID: this.user.studentId,
          courseID: this.courseId,
          chatID
        }
      })
      if (chatID === this.currentChatId) {
        this.currentChatId = null
        this.chatLog = []
      }
      this.loadChatList()
    }
  },
  computed: mapState(['isPractice'])
}
</script>

<style scoped>
.right .icon {
  margin-right: 6px;
}
#student .padding-50 {
  margin: 0 auto;
  padding: 0 50px;
  box-shadow: 0 0 10px 4px rgba(1, 149, 255, 0.1);
  background-color: #fff;
}
.list a {
  text-decoration: none;
  color: #334046;
}
li {
  list-style: none;
  height: 60px;
  line-height: 60px;
}
#student .list {
  display: flex;
}
#student .list li {
  padding: 0 20px;
  cursor: pointer;
}
#student .list li:hover {
  background-color: #0195ff;
  transition: all 0.3s ease;
}
#student .list li:hover a {
  color: #fff;
}
#student .list .right {
  margin-left: auto;
  position: relative;
}
#student .list li.right:hover a {
  color: #000;
}
#student .list .logo {
  display: flex;
  font-weight: bold;
  color: #2f6c9f;
}
#student .list .logo i {
  font-size: 50px;
}
.right .msg {
  text-align: center;
  position: absolute;
  top: 60px;
  right: 0;
  display: flex;
  flex-direction: column;
  border-radius: 2px;
  border-bottom: 3px solid #0195ff;
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 10;
}
.right .msg p {
  height: 40px;
  line-height: 40px;
  width: 105px;
}
.right .msg p:hover {
  background-color: #0195ff;
  color: #fff;
}
.main {
  padding: 20px 50px;
  background-color: #f9f9f9;
  min-height: 500px; /* Added for better layout */
}

.file-link {
  color: #409EFF;
  cursor: pointer;
}

.file-link:hover {
  text-decoration: underline;
}

.dialog-footer {
  text-align: right;
}

.empty-hint {
  padding: 30px;
  text-align: center;
  color: #999;
  font-size: 16px;
}
.chat-container {
  display: flex;
  height: 600px;
  border: 1px solid #e4e4e4;
  background: #fff;
}
.chat-sidebar {
  width: 250px;
  border-right: 1px solid #ccc;
  padding: 10px;
  box-sizing: border-box;
  background: #f6f8fa;
  overflow-y: auto; /* ✅ 添加滚动 */
}
.chat-history {
  list-style: none;
  padding: 0;
  margin-top: 10px;
}
.chat-history li {
  padding: 8px;
  border-bottom: 1px solid #ddd;
  cursor: pointer;
  position: relative;
}
.chat-history li.active {
  background: #dbeeff;
}
.chat-history li:hover {
  background: #ecf5ff;
}
.chat-history i {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  color: red;
}
.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 100%; /* ✅ 保持撑满父容器 */
}
.chat-log {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}
.chat-user {
  text-align: right;
  margin-bottom: 10px;
}
.chat-ai {
  text-align: left;
  margin-bottom: 10px;
}
.chat-content {
  display: inline-block;
  max-width: 70%;
  padding: 10px;
  border-radius: 10px;
  background: #e1f3ff; /* 默认是 AI 的背景 */
}

/* 学生（用户）发出的消息是蓝色 */
.chat-user .chat-content {
  background: #cdefff;
}

/* AI 回复的消息改为白色框 */
.chat-ai .chat-content {
  background: #e7e7e7;
  
}
.chat-input {
  padding: 10px;
  border-top: 1px solid #ccc;
  display: flex;
  gap: 10px;
}
.chat-empty {
  padding: 30px;
  color: #888;
  text-align: center;
}
</style>
